package br.com.jmmarca.controller;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import br.com.jmmarca.dao.impl.VisitanteDAO;
import br.com.jmmarca.model.Visitante;
import br.com.jmmarca.util.EnumRequisicao;

public class LoginVisitante extends Activity {

	private static final String TAG_LOG = "App_Login";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_visitante);

		Log.w(TAG_LOG, "onCreate!");
		// configurando o botão de criar novo cadastro
		Button btnNovo = (Button) findViewById(R.id.btn_vis_enviar);
		btnNovo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				action_validar_usuario();
			}
		});

		Button btnCadastrar = (Button) findViewById(R.id.btn_vis_cadastrar);
		btnCadastrar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent goToNextActivity = new Intent(getApplicationContext(),
						CrudVisitanteBasico.class);
				startActivityForResult(goToNextActivity,EnumRequisicao.CADASTRO_VISITANTE.getKey());
			}
		});
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == EnumRequisicao.CADASTRO_VISITANTE.getKey()) {
			if (resultCode == RESULT_OK) {
				Integer idVisitante = data.getIntExtra("idVisitante", 0);
				if (idVisitante != null && idVisitante != 0) {
					// Inicia a apresentacao para o visitante
					VisitanteDAO visitanteDAO = VisitanteDAO
							.getInstance(getApplicationContext());
					Visitante visitante = visitanteDAO.encontrar(idVisitante);
					Intent goToNextActivity = new Intent(
							getApplicationContext(), MainExposicao.class)
							.putExtra("idVisitante", visitante.getId());
					startActivity(goToNextActivity);
				}
			}
			if (resultCode == RESULT_CANCELED) {
				// Write your code if there's no result

			}
		}
	}// onActivityResult

	public void action_validar_usuario() {
		EditText edtemail = (EditText) findViewById(R.id.txt_vis_email);

		String email = edtemail.getText().toString();

		VisitanteDAO visitanteDAO = VisitanteDAO
				.getInstance(getApplicationContext());
		Visitante visitante;
		try {

			visitante = visitanteDAO.getByClause("email = ?",
					new String[] { email });
		} catch (Exception e) {
			// TODO: handle exception
			visitante= null;
		}

		if (visitante != null) {
			Log.w(TAG_LOG, "action_validar_usuario!");
			Intent goToNextActivity = new Intent(getApplicationContext(),
					MainExposicao.class).putExtra("idVisitante",
					visitante.getId());
			startActivity(goToNextActivity);
		} else {
			Toast msg = Toast.makeText(this, "E-mail não encontrado, Caso seja necessário efetue seu cadastro!",
					Toast.LENGTH_LONG);
			msg.show();
		}
	}
}
